package com.bigscreen.bigScreen.server.exception;

import com.bigscreen.bigScreen.server.utils.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.xml.bind.ValidationException;
import java.security.GeneralSecurityException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * 全局异常拦截通用处理
 *
 * @author zwj
 */
@ControllerAdvice
@ResponseBody
@Slf4j
public class DefaultExceptionAdvice {

    /**
     * IllegalArgumentException异常处理返回json
     * 返回状态码:400
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler({IllegalArgumentException.class})
    public ResponseResult<?> handleIllegalArgumentException(IllegalArgumentException e) {
        return defHandler("参数解析失败", e);
    }


    /**
     * IllegalArgumentException异常处理返回json
     * 返回状态码:400
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler({HttpMessageNotReadableException.class})
    public ResponseResult<?> handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
        return defHandler("反序列化异常", e);
    }

    /**
     * 参数校验异常处理返回json
     * 返回状态码:400
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler({BindException.class, ValidationException.class, MethodArgumentNotValidException.class})
    public ResponseResult<?> bindException(Exception e) {
        List<String> list = new ArrayList<>();
        List<ObjectError> errors = null;
        if (e instanceof BindException) {
            errors = ((BindingResult) e).getAllErrors();
        }else if (e instanceof MethodArgumentNotValidException){
            errors = ((MethodArgumentNotValidException) e).getBindingResult().getAllErrors();
        }
        if (errors != null) {
            for (ObjectError error : errors) {
                list.add(error.getDefaultMessage());
            }
        }
        return defHandler("请填写正确的参数信息："+ list.toString(), e);
    }


    /**
     *
     * @param e RSA异常
     * @return ResponseResult
     */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler({InvalidKeySpecException.class, NoSuchAlgorithmException.class})
    public ResponseResult<?> rsaException(GeneralSecurityException e) {
        if (e instanceof InvalidKeySpecException) {
            return defHandler("密钥错误", e);
        }
            return defHandler("不支持的算法", e);
    }

    /**
     * 返回状态码:405
     */
    @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
    @ExceptionHandler({HttpRequestMethodNotSupportedException.class})
    public ResponseResult<?> handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
        return defHandler("不支持当前请求方法", e);
    }

    /**
     * 返回状态码:415
     */
    @ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
    @ExceptionHandler({HttpMediaTypeNotSupportedException.class})
    public ResponseResult<?> handleHttpMediaTypeNotSupportedException(HttpMediaTypeNotSupportedException e) {
        return defHandler("不支持当前媒体类型", e);
    }

    /**
     * 返回状态码:500
     */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler({SQLException.class})
    public ResponseResult<?> handleSQLException(SQLException e) {
        return defHandler("服务运行SQLException异常", e);
    }



    /**
     * ArithmeticException 算数异常
     * 返回状态码:500
     */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(ArithmeticException.class)
    public ResponseResult<?> handleException(ArithmeticException e) {
        return defHandler("算数异常", e);
    }


    /**
     * 所有异常统一处理
     * 返回状态码:500
     */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    public ResponseResult<?> handleException(Exception e) {
        return defHandler("Exception未知异常", e);
    }


    private ResponseResult<?> defHandler(Integer code ,String msg, Exception e) {
        //log.error(msg, e);
        return ResponseResult.failed(code,msg);
    }

    private ResponseResult<?> defHandler(String msg, Exception e) {
        //log.error(msg, e);
        return ResponseResult.failed(msg);
    }

}
